package com.lujieni.test.testechoserver;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        // 用bootstrap连接netty服务端
        Channel cf = new Bootstrap()
                .group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf bb = (ByteBuf) msg;
                                System.out.println(bb.toString(StandardCharsets.UTF_8));
                            }
                        });
                    }
                })
                .connect("localhost", 8081)
                .sync().channel();

        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String s = scanner.nextLine();
                if("q".equals(s)){
                    cf.close();
                    break;
                }else{
                    cf.writeAndFlush(s);
                }
            }

        }, "input").start();

        //当连接关闭后添加一个监听
        cf.closeFuture().addListener(future -> {
            System.out.println("客户端关闭");
            nioEventLoopGroup.shutdownGracefully();
        });
    }

}
